package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.dao.userDao;
import org.example.vo.ApiResponse;
import org.example.vo.UserVO;
import org.example.vo.accountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @Description
 * @Author 魏锴
 * @Date 2023/12/2
 */

@Slf4j
@Controller
public class UserController {
    @Autowired
    private userDao userDao;

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("msg", "你好");
        return "hello";
    }

    @GetMapping("/login")
    public String login() {
        log.info("to login page.");
        return "user/login";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public ApiResponse doLogin(HttpSession session,Model model, @RequestBody accountVO account) {
        log.info("login:({})", account);
        if (userDao.login(account.getUsername(), account.getPassword())) {
            session.setAttribute("localUser", userDao.getUser(account.getUsername()));
            return ApiResponse.ok("登录成功");
        } else return ApiResponse.failure("账号或密码错误");
    }
    @GetMapping("/register")
    public String register(){
        log.info("to register Page.");
        return "user/register";
    }

    @PostMapping("/doRegister")
    @ResponseBody
    public ApiResponse register(Model model, @RequestBody UserVO userVO) {
        log.info("doRegister:{}", userVO);
        if (userDao.register(userVO)) return ApiResponse.ok("注册成功");
        else return ApiResponse.failure("注册失败");
    }

    @RequestMapping("/show")
    public String showUser(HttpSession session,Model model){
        model.addAttribute("showUser",session.getAttribute("localUser"));
        return "user/show";
    }
}
